package com.uphone.kingmall.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.transition.Slide;
import android.util.Pair;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.china.zhuoyue.R;
import com.gyf.barlibrary.ImmersionBar;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.uphone.kingmall.listener.PermissionListener;
import com.uphone.kingmall.utils.ActivityCollector;
import com.uphone.kingmall.utils.SDKUtils;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

import static com.uphone.kingmall.app.MyApplication.api;


/******************************************
 * 类描述： Activity基类 类名称：BaseActivity
 *
 * @version: 1.0
 * @author: shaoningYang
 * @time: 2017-3-10 09:43
 ******************************************/

public abstract class BaseActivity extends AppCompatActivity {

    private static final String TAG = "BaseActivity";

    //    private ImageView mLoadingImageView;
//    private ShapeRipple mShapeRipple;
//    private Animation mLoadingAnimation;

    //    private LoadingFailedView mLoadingFailedView;
    private TextView mLoadingFailedTextView;

    public static final int NONE_JUMP_TYPE = 0x0;
    public static final int DEFAULT_JUMP_TYPE = 0x1;
    public static final int BOTTOM_JUMP_TYPE = 0x2;
    public static final int RIGHT_IN_LEFT_OUT_TYPE = 0x3;
    public static final int ALPHA_ANIMATION_TYPE = 0x4;

    private int mPageJumpType = DEFAULT_JUMP_TYPE;
    /**
     * 是否可以使用沉浸模式true为是，false为否
     */
    private boolean canUseStatusBarCompat = SDKUtils.hasLOLLIPOP();
    /**
     * 是否可以使用butterKnife true为是，false为否
     */
    private boolean canUseButterKnife = true;
    /**
     * 是否可以使用EventBus true为是，false为否
     */
    private boolean canUseEventBus;

    /**
     * 点击空白区域隐藏键盘 true为是，false为否
     */
    private boolean canHiddenSoftKeyboardOnTouch;

    /**
     * 是否可以使用Android5.0提供的Activity转场动画 true为是，false为否
     */
    private static boolean canUseAndroidLOLLIPOPAnim = false;//SDKUtils.hasLOLLIPOP();


    //动态权限参数
    private PermissionListener mListener;
    private static final int PERMISSION_REQUESTCODE = 100;
    //状态栏工具
    public ImmersionBar mImmersionBar;
    public boolean isUseImmersionBar = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
        setUpWindowEnterTransitionForLOLLIPOP();
//        getWindow().setBackgroundDrawable(null);

        int contentId = getLayoutContentId();
        if (contentId > 0) {
            setContentView(contentId);
            try {
                IntentUtils.init(this);
            } catch (IllegalAccessException e) {
                LogUtils.e("intent异常：" + e.toString());
                e.printStackTrace();
            }
        }
        AfterLayout(savedInstanceState);
        mImmersionBar = ImmersionBar.with(this);
        if (isUseImmersionBar) {
            setImmersionBar();
        } else {
            setStatusBar();
        }

        initOtherData();
        initView();
        initData();
    }

    protected void AfterLayout(Bundle savedInstanceState) {

    }

    public void setImmersionBar() {
        //防止设置状态栏后  软键盘怎么设置也不会把布局顶上去
        mImmersionBar.keyboardEnable(true, WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN).navigationBarWithKitkatEnable(false).init();
//            mImmersionBar.init();   //所有子类都将继承这些相同的属性
//        mImmersionBar
////                    .fitsSystemWindows(true)
////                .statusBarView(statusBar)
//                .statusBarColor(R.color.colorTransparent)
//                .statusBarDarkFont(false, 0.2f)
//                .navigationBarColor(R.color.colorTransparent)
//                .fullScreen(false)
//                .init();
        mImmersionBar
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0.2f)
                .statusBarColor(R.color.colorPrimaryDark)
                .navigationBarColor(R.color.black)
                .fullScreen(false)
                .init();
    }


    /**
     * 设置状态栏
     */
    public void setStatusBar() {
        mImmersionBar
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0.2f)
                .statusBarColor(R.color.colorPrimaryDark)
                .navigationBarColor(R.color.black)
                .fullScreen(false)
                .init();
    }


    public void setStatusBar(int viewID) {
        mImmersionBar.statusBarView(viewID)
//                .statusBarColor(color)
                .statusBarDarkFont(true, 0.2f)
                .navigationBarColor(R.color.black)
                .fullScreen(false)
                .init();
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void setUpWindowEnterTransitionForLOLLIPOP() {
        if (canUseAndroidLOLLIPOPAnim) {
            Slide slide = new Slide();
            slide.setSlideEdge(mPageJumpType == BOTTOM_JUMP_TYPE ? Gravity.BOTTOM : Gravity.RIGHT);
            slide.setDuration(getResources().getInteger(R.integer.anim_duration_long));
            getWindow().setEnterTransition(slide);
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void setUpWindowExitTransitionForLOLLIPOP() {
        if (canUseAndroidLOLLIPOPAnim) {
            Slide slide = new Slide();
            slide.setSlideEdge(mPageJumpType == BOTTOM_JUMP_TYPE ? Gravity.TOP : Gravity.LEFT);
            slide.setDuration(getResources().getInteger(R.integer.anim_duration_long));
            getWindow().setExitTransition(slide);
        }
    }


    /**
     * 初始化其他辅助业务逻辑
     */
    private void initOtherData() {
        if (canUseButterKnife) {
            ButterKnife.bind(this);
        }
//        if (canUseStatusBarCompat) {
//            StatusBarCompat.compat(this, SDKUtils.getColor(this, getStatusBarColor()));
//        }
        if (canUseEventBus) {
            EventBus.getDefault().register(this);
        }
    }

    public void setPageJumpType(int pageJumpType) {
        this.mPageJumpType = pageJumpType;
    }

    protected int getStatusBarColor() {
        return R.color.colorWhite;
    }

    /**
     * 禁用沉浸模式
     */
    protected void disableStatusBarCompat() {
        canUseStatusBarCompat = false;
    }

    /**
     * 启用EventBus功能
     */
    protected void enableEventBus() {
        canUseEventBus = true;
    }

    /**
     * 启用触摸空白区域使软键盘隐藏
     */
    protected void enableHiddenSoftKeyboardOnTouch() {
        canHiddenSoftKeyboardOnTouch = true;
    }

    /**
     * 禁用butterKnife功能
     */
    protected void disableButterKnife() {
        canUseButterKnife = false;
    }

    public abstract int getLayoutContentId();

    public abstract void initView();

    public abstract void initData();

    protected void retryGetData() {
        hiddenLoadingFailed();
    }

    public void showLoadingView() {
//        if (mShapeRipple == null) {
//            ViewStub viewStub = (ViewStub) findViewById(R.id.loading_view_viewStub);
//            viewStub.inflate();
//            mShapeRipple = (ShapeRipple) findViewById(R.id.loading_shapeRipple);
//            mShapeRipple.setRippleShape(new Circle());
//        } else {
//            View view = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
//            if (view instanceof ViewGroup) {
//                ViewGroup viewGroup = (ViewGroup) view;
//                ViewGroup childViewGroup = (ViewGroup) mShapeRipple.getParent();
//                viewGroup.removeView(childViewGroup);
//                viewGroup.addView(childViewGroup);
//                mShapeRipple.startRipple();
//            }
//        }
//        if (mLoadingFailedView != null && mLoadingFailedView.getParent() != null) {
//            hiddenLoadingFailed();
//        }
    }

    /**
     * 判断是否缺少权限
     */
    public boolean lacksPermission(Context mContexts, String permission) {
        return ContextCompat.checkSelfPermission(mContexts, permission) ==
                PackageManager.PERMISSION_DENIED;
    }

    public void hiddenLoading() {
//        if (mShapeRipple == null) {
//            return;
//        }
//        mShapeRipple.stopRipple();
//        View view = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
//        if (view instanceof ViewGroup) {
//            ((ViewGroup) view).removeView((ViewGroup) mShapeRipple.getParent());
//        }
    }

    public void setLoadingFailedBg(int resId) {
//        if (mLoadingFailedView != null) {
//            mLoadingFailedView.setBackgroundResource(resId);
//        }
    }

    /**
     * @param errorType (参考Constants.NO_NET_ERROR,Constants.NO_DATA_ERROR)
     */
    public void showLoadingFailedView(int errorType) {
//        if (mLoadingFailedView == null) {
//            ViewStub viewStub = (ViewStub) findViewById(R.id.loading_failed_view_viewStub);
//            viewStub.inflate();
//            mLoadingFailedView = (LoadingFailedView) findViewById(R.id.loading_failed_main_layout);
//            mLoadingFailedTextView = (TextView) findViewById(R.id.loading_failed_textView);
//
//            mLoadingFailedTextView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
//            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mLoadingFailedTextView.getLayoutParams();
//            layoutParams.topMargin = DeviceUtils.getScreenWidthAndHeight(this, false) / 2
//                    - getResources().getDimensionPixelOffset(R.dimen.title_layout_height) - mLoadingFailedTextView.getMeasuredHeight();
//
//            mLoadingFailedView.setOnClickListener(new MyDebouncingOnClickListener() {
//                @Override
//                public void doClick(View v) {
//                    int errorType = Integer.parseInt(v.getTag().toString());
//                    if (errorType == Constants.NO_DATA_SHOP_CART_ERROR) {
//                        return;
//                    }
//                    ViewUtils.setViewVisibility(mLoadingFailedView, View.GONE);
//                    retryGetData();
//                }
//            });
//        } else {
//            View view = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
//            if (view instanceof ViewGroup) {
//                ViewGroup viewGroup = (ViewGroup) view;
//                viewGroup.removeView(mLoadingFailedView);
//                ViewUtils.setViewVisibility(mLoadingFailedView, View.VISIBLE);
//                viewGroup.addView(mLoadingFailedView);
//            }
//        }
//        mLoadingFailedView.setTag(errorType);
//        if (errorType == Constants.NO_NET_ERROR) {
//            mLoadingFailedTextView.setText(R.string.no_netWork_error_str);
//            mLoadingFailedTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.no_net_error_icon, 0, 0);
//        } else if (errorType == Constants.NO_DATA_SEARCH_ERROR) {
//            mLoadingFailedTextView.setText(R.string.no_search_error_str);
//            mLoadingFailedTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.no_search_data_error_icon, 0, 0);
//        } else if (errorType == Constants.NO_DATA_SHOP_CART_ERROR) {
//            mLoadingFailedTextView.setText(R.string.no_data_shop_cart_error_str);
//            mLoadingFailedTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.no_shop_cart_data_error_icon, 0, 0);
//        } else {
//            mLoadingFailedTextView.setText(R.string.no_data_warning_str);
//            mLoadingFailedTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.no_data_error_icon, 0, 0);
//        }

//        if (mShapeRipple != null && mShapeRipple.getParent() != null && mShapeRipple.getParent().getParent() != null) {
//            hiddenLoading();
//        }
    }

    public void hiddenLoadingFailed() {
//        if (mLoadingFailedView == null) {
//            return;
//        }
//        View view = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
//        if (view instanceof ViewGroup) {
//            ((ViewGroup) view).removeView(mLoadingFailedView);
//        }
    }

//    public boolean isLoadingViewShow() {
//        return mShapeRipple != null && mShapeRipple.getParent() != null && mShapeRipple.getParent().getParent() != null;
//    }

    @Override
    public void onBackPressed() {
//        if (isLoadingViewShow()) {
//            hiddenLoading();
//            return;
//        }
        super.onBackPressed();
        if (canUseAndroidLOLLIPOPAnim) {
            setUpWindowExitTransitionForLOLLIPOP();
            return;
        }
//        if (mPageJumpType == BOTTOM_JUMP_TYPE) {
//            overridePendingTransition(0, R.anim.push_bottom_out);
//        } else if (mPageJumpType == RIGHT_IN_LEFT_OUT_TYPE) {
//            overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
//        } else if (mPageJumpType == DEFAULT_JUMP_TYPE) {
//            overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
//        } else {
//
//        }
    }

    @Override
    public void startActivity(Intent intent) {
//        if (canUseAndroidLOLLIPOPAnim) {
//            startActivityForLOLLIPOP(intent);
//            return;
//        }
        super.startActivity(intent);
//        if (mPageJumpType == BOTTOM_JUMP_TYPE) {
//            overridePendingTransition(R.anim.push_bottom_in, 0);
//        } else if (mPageJumpType == ALPHA_ANIMATION_TYPE) {
//            overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);
//        } else {
//            overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
//        }
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
//        if (canUseAndroidLOLLIPOPAnim) {
//            startActivityForResultForLOLLIPOP(intent, requestCode);
//            return;
//        }
//        if (mPageJumpType == BOTTOM_JUMP_TYPE) {
//            overridePendingTransition(R.anim.push_bottom_in, 0);
//        } else {
//            overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
//        }
    }

    public void startActivityTransitionViews(Intent intent, View... views) {
        if (SDKUtils.hasLOLLIPOP()) {
            startActivityTransitionViewsForLOLLIPOP(intent, views);
        } else {
            startActivity(intent);
        }
    }

    public void startActivityForResultTransitionViews(Intent intent, int requestCode, View... views) {
        if (SDKUtils.hasLOLLIPOP()) {
            startActivityForResultTransitionViewsForLOLLIPOP(intent, requestCode, views);
        } else {
            startActivityForResult(intent, requestCode);
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void startActivityForLOLLIPOP(Intent intent) {
        super.startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void startActivityForResultForLOLLIPOP(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void startActivityTransitionViewsForLOLLIPOP(Intent intent, View... views) {
        if (views != null && views.length > 0) {
            Pair[] pairs = new Pair[views.length];
            for (int i = 0; i < pairs.length; i++) {
                View view = views[i];
                String transitionName = view.getTransitionName();
                pairs[i] = Pair.create(view, transitionName);
            }
            startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this, pairs).toBundle());
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void startActivityForResultTransitionViewsForLOLLIPOP(Intent intent, int requestCode, View... views) {
        if (views != null && views.length > 0) {
            Pair[] pairs = new Pair[views.length];
            for (int i = 0; i < pairs.length; i++) {
                View view = views[i];
                String transitionName = view.getTransitionName();
                pairs[i] = Pair.create(view, transitionName);
            }
            startActivityForResult(intent, requestCode, ActivityOptions.makeSceneTransitionAnimation(this, pairs).toBundle());
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    protected void clearTransition(View view) {
        if (SDKUtils.hasLOLLIPOP()) {
            view.setTransitionName(null);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (canHiddenSoftKeyboardOnTouch) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                View v = getCurrentFocus();
                if (isShouldHideKeyboard(v, ev)) {
                    hideKeyboard(v.getWindowToken());
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 同样是隐藏软键盘
     */
    public void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        //Find the currently focused view, so we can grab the correct window token from it.
        View view = getCurrentFocus();
        //If no view currently has focus, create a new one, just so we can grab a window token from it
        if (view == null) {
            view = new View(this);
        }
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 同样是隐藏软键盘
     */
    public void hideKeyboard1() {
        View v = getCurrentFocus();
        hideKeyboard(v.getWindowToken());

    }

    /**
     * 不带参跳转
     *
     * @param targetActivityClass
     */
    public void openActivity(Class<?> targetActivityClass) {
        Intent intent = new Intent();
        intent.setClass(this, targetActivityClass);
        startActivity(intent);
    }

    /**
     * 带参跳转
     *
     * @param targetActivityClass
     * @param bundle
     */
    public void openActivity(Class<?> targetActivityClass, Bundle bundle) {
        Intent intent = new Intent(this, targetActivityClass);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 检测用户是否登录
     *
     * @return true为登录，false未登录
     */
    public boolean canShowLoginPage() {
//        if (!UserHelper.getInstance().isUserLogin()) {
//            Intent intent = new Intent(this, LoginActivity.class);
//            startActivity(intent);
//            return true;
//        } else {
//            return false;
//        }
        return false;
    }


    /**
     * 权限申请
     */
    public void requestRunPermisssion(String[] permissions, PermissionListener listener) {

        if (mListener != null) {
            mListener = listener;
        }
        List<String> permissionLists = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(permission);
            }
        }

        if (!permissionLists.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), PERMISSION_REQUESTCODE);
        } else {
            //表示全都授权了
            if (mListener != null) {
                mListener.onGranted();
            }
        }
    }

//    /**
//     * 申请权限的回调
//     *
//     * @param requestCode
//     * @param permissions
//     * @param grantResults
//     */
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            case PERMISSION_REQUESTCODE:
//                if (grantResults.length > 0) {
//                    //存放没授权的权限
//                    List<String> deniedPermissions = new ArrayList<>();
//                    for (int i = 0; i < grantResults.length; i++) {
//                        int grantResult = grantResults[i];
//                        String permission = permissions[i];
//                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
//                            deniedPermissions.add(permission);
//                        }
//                    }
//                    if (deniedPermissions.isEmpty()) {
//                        //说明都授权了
//                        if (mListener != null) {
//                            mListener.onGranted();
//                        }
//                    } else {
//                        if (mListener != null) {
//                            mListener.onDenied(deniedPermissions);
//                        }
//                    }
//                }
//                break;
//            default:
//                break;
//        }
//    }

    @Override
    protected void onDestroy() {

        if (canUseEventBus) {
            EventBus.getDefault().unregister(this);
        }
        if (mImmersionBar != null) {
            mImmersionBar.destroy(); //必须调用该方法，防止内存泄漏
        }
        ActivityCollector.removeActivity(this);
        super.onDestroy();
    }

    /**
     * 验证是否是手机号码
     *
     * @param str
     * @return
     */
//    public boolean isMobile(String str) {
////        boolean matches = str.matches(RxConstTool.REGEX_MOBILE_SIMPLE);
//        return matches;
//
//    }
    /**
     * 验证是否是邮箱
     *
     * @param str
     * @return
     */
//    public boolean isEMail(String str) {
//        boolean matches = str.matches(RxConstTool.REGEX_EMAIL);
//        return matches;
//    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        MobclickAgent.onResume(this);
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        MobclickAgent.onPause(this);
//    }

    /**
     * 检测GPS是否打开
     *
     * @return
     */
    public boolean checkGPSIsOpen() {
        boolean isOpen;
        android.location.LocationManager locationManager = (android.location.LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
        return isOpen;
    }

    /**
     * 通过设置全屏，设置状态栏透明
     */
    public void fullScreen(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
                //导航栏颜色也可以正常设置
//                window.setNavigationBarColor(Color.TRANSPARENT);
            } else {
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
                attributes.flags |= flagTranslucentStatus;
//                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }
    }


    //Toast显示
    protected void showShortToast(String string) {
        ToastUtils.showShortToast(this, string);
    }

    protected void showShortToast(int stringId) {
        ToastUtils.showShortToast(this, stringId);
    }

    protected void showLongToast(String string) {
        ToastUtils.showShortToast(this, string);
    }

    protected void showLongToast(int stringId) {
        ToastUtils.showShortToast(this, stringId);
    }

    public void onPayPsdSuccess(String passWord) {

    }

    public void wxPaySuccess() {
    }


    public void loadJPush() {
    }



    private Bitmap thumbBmp = null;
    private PopupWindow pop;

    public void showSharePop(final View root,final String url, final String title, final String detail, final String imgurl) {
        thumbBmp = null;
        View view = getLayoutInflater().inflate(R.layout.kingmall_pop_share, null);
        LinearLayout parent = (LinearLayout) view.findViewById(R.id.parent);
        TextView tv_wechat = (TextView) view.findViewById(R.id.tv_wechat);
        TextView tv_wechat_circle = (TextView) view.findViewById(R.id.tv_wechat_circle);
        TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        Glide.with(BaseActivity.this).asBitmap().load(imgurl).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                if (resource.getHeight() > 100 && resource.getWidth() > 100) {
                    thumbBmp = Bitmap.createScaledBitmap(resource, 100, 100, true);
                } else {
                    thumbBmp = resource;
                }
                if (thumbBmp != null) {

                } else {
                    thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);
                    ToastUtils.showShortToast(BaseActivity.this, "获取分享图片失败！");
                }
            }
        });

        parent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
            }
        });
        tv_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
                shareUrlToWechat(0, url, title, detail);
            }
        });
        tv_wechat_circle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
                shareUrlToWechat(1, url, title, detail);
            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();

            }
        });
        pop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setFocusable(true);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.showAtLocation(root, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 发送带Url的微信
     *
     * @param key 0好友，1朋友圈
     * @return
     */
    public boolean shareUrlToWechat(int key, String shareUrl, String title, String message) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        String description = "";
        if (message.length() > 30) {
            description = message.substring(0, 30) + "...";
        } else {
            description = message;
        }
        msg.description = description;

        if (thumbBmp == null) {
            thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);
        }
        msg.thumbData = bitmapBytes(thumbBmp, true);
        thumbBmp = null;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = (key == 0) ? SendMessageToWX.Req.WXSceneSession
                : SendMessageToWX.Req.WXSceneTimeline;
        return api.sendReq(req);

    }

    public byte[] bitmapBytes(final Bitmap bmp, final boolean needRecycle) {
        if (bmp == null) {
            return null;
        }
        int i;
        int j;
        if (bmp.getHeight() > bmp.getWidth()) {
            i = bmp.getWidth();
            j = bmp.getWidth();
        } else {
            i = bmp.getHeight();
            j = bmp.getHeight();
        }

        Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
        Canvas localCanvas = new Canvas(localBitmap);

        while (true) {
            localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i, j), null);
            if (needRecycle)
                bmp.recycle();
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            } catch (Exception e) {
                //F.out(e);
            }
            i = bmp.getHeight();
            j = bmp.getHeight();
        }
    }


    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }
}
